using UniversalAdminSystem.Domian.Core;
using UniversalAdminSystem.Domian.Core.ValueObjects;
using UniversalAdminSystem.Domian.FileStorage.ValueObjects;

namespace UniversalAdminSystem.Domian.FileStorage.Aggregates;

public class File : AggregateRoot
{
    public FileId Id { get; private set; }
    public FileName Name { get; private set; }
    public FilePath Path { get; private set; }
    public FileSize Size { get; private set; }
    public FileType Type { get; private set; }
    public UserId OwnerId { get; private set; }
    public DateTime UploadTime { get; private set; }
    public bool IsFolder { get; private set; }
    public FileId? ParentId { get; private set; }
    public FileAccessLevel AccessLevel { get; private set; }
    public string? SecurityCheckResult { get; private set; }

    private File() { }

    public static File Create(
        FileName name, 
        FilePath path, 
        FileSize size, 
        FileType type, 
        UserId ownerId, 
        bool isFolder = false, 
        FileId? parentId = null, 
        FileAccessLevel accessLevel = FileAccessLevel.Private
    )
    {
        if (size.Value > FileSize.MaxSize) throw new ArgumentException($"文件大小不能超过{FileSize.MaxSize / 1024 / 1024}MB");
        return new File
        {
            Id = FileId.Create(),
            Name = name,
            Path = path,
            Size = size,
            Type = type,
            OwnerId = ownerId,
            UploadTime = DateTime.UtcNow,
            IsFolder = isFolder,
            ParentId = parentId,
            AccessLevel = accessLevel
        };
    }

    public void SetSecurityCheckResult(string result)
    {
        SecurityCheckResult = result;
    }

    public void Rename(FileName newName)
    {
        Name = newName;
    }

    public void Move(FileId? newParentId)
    {
        ParentId = newParentId;
    }

    public void ChangeAccessLevel(FileAccessLevel accessLevel)
    {
        AccessLevel = accessLevel;
    }

    public bool CanAccess(UserId userId, bool isSuperAdmin, bool isAdmin)
    {
        if (isSuperAdmin) return true;
        if (isAdmin)
        {
            // 管理员可访问公开和受限文件
            return AccessLevel == FileAccessLevel.Public || AccessLevel == FileAccessLevel.Restricted || OwnerId == userId;
        }
        // 普通用户只能访问公开文件或自己拥有的文件
        return AccessLevel == FileAccessLevel.Public || OwnerId == userId;
    }
} 